package com.pickgliss.loader
{
	import com.pickgliss.ui.core.Disposeable;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	import flash.utils.Dictionary;

	[Event(name="complete",type="flash.events.Event")]
	[Event(name="change",type="flash.events.Event")]
	public class QueueLoaderII extends EventDispatcher implements Disposeable
	{
		
		public function QueueLoaderII()
		{
			_loaders = new Vector.<BaseLoader>();
			_progress = new Dictionary(true);
		}
		
		private var _loaders:Vector.<BaseLoader>;
		private var _progress : Dictionary ;
		
		public function addLoader(loader:BaseLoader):void
		{
			_loaders.push(loader);
			_progress[loader.url] = 0;
			loader.addEventListener(LoaderEvent.PROGRESS, __progressHandler);
			loader.addEventListener(LoaderEvent.COMPLETE, __loadCompleteHandler);
			
		}
		public function startLoads() : void
		{
			for each(var load : BaseLoader in _loaders) 
			{
				LoaderManager.Instance.startLoad(load);
			}
		}
		
		public function get progress() : Number
		{
			var count : int;
			var pro   : Number = 0;
			for(var key : String in _progress)
			{
				count ++;
				pro += Number(_progress[key]);
			}
			return pro / count;
		}
		
		private function __progressHandler(evt : LoaderEvent) : void
		{
			_progress[evt.loader.url] = evt.loader.progress;
			dispatchEvent(new Event(Event.CHANGE));
		}
		private function __loadCompleteHandler(evt : LoaderEvent) : void
		{
			_progress[evt.loader.url] = 1;
			var pro : Number = progress;
			if(pro >= 1)dispatchEvent(new Event(Event.COMPLETE));
		}
		public function dispose() :void
		{
			for each(var loader : BaseLoader in _loaders) 
			{
				loader.removeEventListener(LoaderEvent.PROGRESS, __progressHandler);
				loader.removeEventListener(LoaderEvent.COMPLETE, __loadCompleteHandler);
			}
			while(_loaders.length >0)_loaders.pop();
		}
		
		
	}
}